package gbench.appdemo.trading.agent;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import gbench.appdemo.trading.position.TradingPositionBill;
import gbench.appdemo.trading.position.TradeItem;
import gbench.appdemo.trading.position.TradingPositionBill.TradingPostion;
import gbench.appdemo.trading.proxy.ServiceProxy;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data @NoArgsConstructor @AllArgsConstructor
public class Agent{
    private String name;// 交易者
    private List<TradeItem> favorites =new ArrayList<TradeItem>();// 兴趣商品
    private Integer credits;// 信用等级
    
     /*
      * 交易长头
      */
    public TradingPositionBill call(TradeItem prod) {
        var pos = new TradingPositionBill();
        return pos;
    }
    
    /**
     * 交易空头
     * @param prod
     * @return
     */
    public TradingPositionBill put(TradeItem prod) {
        var pos = new TradingPositionBill();
        pos.setPosition(TradingPostion.SHORT);// 空头
        return pos;
    }
    
    
    /**
     *  随机头寸
     * @return
     */
    public TradingPositionBill randPosition(Double qty,Double unitPrice) {
        final var bill = new TradingPositionBill();
        bill.setPosition(Math.random()>0.5?TradingPostion.SHORT:TradingPostion.LONG);
        bill.setUnderlying(ServiceProxy.randIt(this.getFavorites()));
        bill.setQuantity(qty);
        bill.setUnitPrice(unitPrice);
        bill.setOwner(this);
        bill.setCreateTime(LocalDateTime.now());
        return bill;
    }
    
    /**
     *  随机头寸
     * @return
     */
    public TradingPositionBill randPosition() {
        var rnd = new Random();
       return this.randPosition(rnd.nextInt(2)+1.0, 4800+(Math.random()>0?-1:1)*Math.random()*1000);
    }
    
    public Agent(String name) {
        this.name = name;
    }
    
    /**
     * 
     * @param products
     */
    public void addFavorites(TradeItem ...products) {
        this.addFavorites(Arrays.asList(products));
    }
    
    /**
     * 
     * @param product
     */
    public void addFavorite(TradeItem product){
        var b = this.favorites.stream().filter(e->e.equals(product)).findAny().isEmpty();
        if(b)this.favorites.add(product);
    }
    
    /**
     * 
     * @param products
     */
    public void addFavorites(List<TradeItem> productStream) {
        productStream.forEach(product->{
            this.favorites.add(product);
        });
    }
    
    public void removeFavorites(TradeItem product) {
        this.favorites.remove(product);
    }
    
    /**
     * 交易头寸
     * @return
     */
    public List<TradingPositionBill> getTradingPositionBills(){
        return ServiceProxy.getInstance().getTradingPositionBills(this);
    }
    
}